# -*- coding: utf-8 -*-
#generate_post_task.py

import wsgiref.handlers
from google.appengine.ext import webapp
import sys, time, uuid
import os
from google.appengine.ext.webapp import template
from google.appengine.ext import db
from xmw import tianya
from xmw.tianya.bot import *
import xmw
from xmw.tianya import error_tianya
import urllib2

class MainPage(xmw.RequestHandler):
    def get(self):
        e=None
        q=Post_Update_Request.all()
        #q.filter('accept=',True)
        q.filter('is_in_progress =',False)
        q.filter('is_finished =', False)
        
        req=q.get()
        if req is None:
            e=error_tianya.NO_POST_UPDATE_REQUEST('/generate_post_task')
            self.render_error(e)
            return
        
        url=req.url
        page=urllib2.urlopen(url)
        soup=BeautifulSoup(page)
        type=get_page_type(soup)
        page_cnt=get_form_cnt(soup)
        
        lst_url=[]
        lst_url.append(url.encode('ascii'))
        
        #now only support FORM types
        task=Task_ScanPost(page_url=lst_url,type=type,page_cnt=page_cnt)
        task.put()
        
        #change request's status
        req.is_in_progress=True
        req.put()
        e=error_tianya.NEW_SCANPOST_Task('%s'%task.page_url)
        self.render_error(e)
    
def main():
    import global_setting
    
    application = webapp.WSGIApplication(
                                       [('/generate_post_task', MainPage)],
                                       debug=global_setting.is_debug())                                       
    wsgiref.handlers.CGIHandler().run(application)

if __name__ == "__main__":
    main()
